<template>
  <div class="employee-management">
    <div class="header">
      <h2>员工账号管理</h2>
      <el-button type="primary" @click="showAddDialog">添加员工</el-button>
    </div>

    <!-- 员工列表 -->
    <el-table :data="employeeList" style="width: 100%" border v-loading="loading">
      <el-table-column prop="employeeId" label="员工ID" width="100" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
              v-if="scope.row.status !== 'pending'"
            :type="scope.row.status === 'frozen' ? 'success' : 'warning'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 'frozen' ? '解冻' : '冻结' }}
          </el-button>
          <el-button
            v-if="scope.row.status === 'pending'"
            type="success"
            size="small"
            @click="handleApprove(scope.row)"
          >
            审核通过
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="employeeForm" :rules="rules" ref="employeeFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="loginPassword" v-if="dialogType === 'add'">
          <el-input v-model="employeeForm.loginPassword" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogType === 'add'">
          <el-input v-model="employeeForm.confirmPassword" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEmployees, addEmployee, updateEmployee, deleteEmployee, updateEmployeeStatus } from '../../api/employeeApi'

export default {
  name: 'EmployeeManagement',
  setup() {
    const loading = ref(false)
    const employeeList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const employeeFormRef = ref(null)

    const employeeForm = reactive({
      employeeId: '',
      name: '',
      loginPassword: '',
      confirmPassword: ''
    })

    const rules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      loginPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== employeeForm.loginPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 获取员工列表
    const getEmployeeList = async () => {
      loading.value = true
      try {
        const res = await getEmployees({
          pageNum: currentPage.value,
          pageSize: pageSize.value
        })
        if (res.flag) {
          employeeList.value = res.result.records
          total.value = res.result.total
        } else {
          ElMessage.error(res.reason || '获取员工列表失败')
        }
      } catch (error) {
        ElMessage.error('获取员工列表失败')
      } finally {
        loading.value = false
      }
    }

    // 状态类型
    const getStatusType = (status) => {
      const types = {
        active: 'success',
        frozen: 'danger',
        pending: 'warning'
      }
      return types[status] || 'info'
    }

    // 状态文本
    const getStatusText = (status) => {
      const texts = {
        active: '正常',
        frozen: '已冻结',
        pending: '待审核'
      }
      return texts[status] || status
    }

    // 显示添加对话框
    const showAddDialog = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
      employeeForm.employeeId = ''
      employeeForm.name = ''
      employeeForm.loginPassword = ''
      employeeForm.confirmPassword = ''
    }

    // 处理编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      employeeForm.employeeId = row.employeeId
      employeeForm.name = row.name
    }

    // 处理删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确认要删除该员工吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteEmployee(row.employeeId)
        if (res.flag) {
          ElMessage.success('删除成功')
          getEmployeeList()
        } else {
          ElMessage.error(res.reason || '删除失败')
        }
      } catch (error) {
        // 用户取消删除操作
      }
    }

    // 处理状态变更
    const handleStatusChange = async (row) => {
      const newStatus = row.status === 'frozen' ? 'active' : 'frozen'
      try {
        const res = await updateEmployeeStatus({
          id: row.employeeId,
          status: newStatus
        })
        if (res.flag) {
          ElMessage.success('状态更新成功')
          getEmployeeList()
        } else {
          ElMessage.error(res.reason || '状态更新失败')
        }
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    // 处理审核
    const handleApprove = async (row) => {
      try {
        const res = await updateEmployeeStatus({
          id: row.employeeId,
          status: 'active'
        })
        if (res.flag) {
          ElMessage.success('审核通过成功')
          getEmployeeList()
        } else {
          ElMessage.error(res.reason || '审核失败')
        }
      } catch (error) {
        ElMessage.error('审核失败')
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!employeeFormRef.value) return
      
      try {
        await employeeFormRef.value.validate()
        const params = {
          name: employeeForm.name,
          loginPassword: employeeForm.loginPassword
        }
        
        let res
        if (dialogType.value === 'add') {
          res = await addEmployee(params)
        } else {
          params.employeeId = employeeForm.employeeId
          delete params.loginPassword
          res = await updateEmployee(params)
        }
        
        if (res.flag) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
          dialogVisible.value = false
          getEmployeeList()
        } else {
          ElMessage.error(res.reason || (dialogType.value === 'add' ? '添加失败' : '编辑失败'))
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '编辑失败')
      }
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      getEmployeeList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getEmployeeList()
    }

    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    onMounted(() => {
      getEmployeeList()
    })

    return {
      loading,
      employeeList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      employeeForm,
      employeeFormRef,
      rules,
      getStatusType,
      getStatusText,
      showAddDialog,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleApprove,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.employee-management {
  padding: 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  font-size: 24px;
  color: #1e3c72;
  font-weight: 600;
  margin: 0;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #1e3c72;
  font-weight: 600;
  font-size: 14px;
  height: 50px;
}

:deep(.el-table td) {
  padding: 12px 0;
  font-size: 14px;
}

:deep(.el-table--striped .el-table__row--striped td) {
  background: #f9fafc;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: #1e3c72;
  border-color: #1e3c72;
}

:deep(.el-button--primary:hover) {
  background: #2a5298;
  border-color: #2a5298;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(30, 60, 114, 0.2);
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 4px 8px;
  font-weight: 500;
}

/* 分页样式 */
.pagination {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-pagination) {
  justify-content: flex-end;
  padding: 0;
}

:deep(.el-pagination button) {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-pagination .el-pager li) {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 4px;
  min-width: 32px;
}

:deep(.el-pagination .el-pager li.active) {
  background-color: #1e3c72;
  border-color: #1e3c72;
  color: #ffffff;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: #1e3c72;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #1e3c72;
}

:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: #1e3c72;
}

/* 操作按钮组样式 */
:deep(.el-table .cell .el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-table .cell .el-button) {
  padding: 6px 12px;
  font-size: 13px;
}
</style>
